import java.net.InetAddress;
import java.net.UnknownHostException;

/*
 * The Wrapper Facade class that is used for IPv4 commands.
 * This encapsulates the networking interface of the
 * InetAddress class. This could be changed for IPv6,
 * modem communication, etc with out changing
 * any of the code in the other agents!
 */
public class IPv4Wrapper {

	//Returns the addresses for the local computers.
	public static String[] checkForComputers()
	{
		int[] hostIP = getLocalIPAddress();

		String[] localComputers = new String[20];
		int numberOfComputers = 1;
		localComputers[0] = getLocalHost();
		int ipFloor, ipCeiling;
		if(hostIP[3] >= 10) {
			ipFloor = hostIP[3]-10;
		} else {
			ipFloor = 0;
		}
		if(hostIP[3] <= 246) {
			ipCeiling = hostIP[3] + 10;
		} else {
			ipCeiling = 256;
		}

		for(int i = ipFloor; i < ipCeiling; i++)	//Check all IPs 10 below the host IP.
		{
			try{
				InetAddress potentialTarget = InetAddress.getByName(hostIP[0] + "." + hostIP[1] + "." + hostIP[2] + "." + i);
				if(potentialTarget.isReachable(1000))
				{
					localComputers[numberOfComputers] = potentialTarget.getHostAddress();
					System.out.println("Found " + localComputers[numberOfComputers]);
					numberOfComputers++;
				}
			}
			catch(Exception e){
				System.out.println("There's a problem in checkForComputers()");
			}
		}

		return localComputers;
	}

	//Returns the local IP address in an integer array. Each octet of the IP is a value in the array.
	private static int[] getLocalIPAddress()
	{
		InetAddress localIP;
		int[] ipOctets = new int[4];

		try {
			localIP = InetAddress.getLocalHost();
			String ipString = localIP.getHostAddress();	//Creates a string of the IP Address. Ex: 192.168.1.1
			for(int i = 0; i < 3; i++)	//Places each octet of the IP into an integer array. This array is then returned.
			{
				ipOctets[i] = Integer.parseInt(ipString.substring(0, ipString.indexOf('.')));
				ipString = ipString.substring(ipString.indexOf('.') + 1);
			}
			ipOctets[3] = Integer.parseInt(ipString);

		} catch (UnknownHostException e) {
			System.err.println("UnknownHostException: " + e.getMessage());
			e.printStackTrace();
		}
		return ipOctets;
	}

	//Returns the IPv4 string representation of the local IPAddress.
	public static String getLocalHost()
	{
		int[] ipOctets = getLocalIPAddress();
		return ipOctets[0] + "." + ipOctets[1] + "." + ipOctets[2] + "." + ipOctets[3];
	}

	public static String[] checkComputersForRunningStories(String[] computerList) {
		String[] storyComputers = new String[computerList.length];
		int numberOfStoryComputers = 0;
		for(int i = 0; i < computerList.length; i++)
		{
			if(computerList[i] != null)
			{
				if(NetCommunicationWrapper.checkConnectability(computerList[i]))
				{

					storyComputers[numberOfStoryComputers] = computerList[i];
					numberOfStoryComputers++;
				}

			}
		}
		return storyComputers;
	}
}